//
//  KSPickerOrderChooseView.swift
//  Supermarket
//
//  Created by Black_Crystal on 2017/9/25.
//  Copyright © 2017年 kushao. All rights reserved.
//

import UIKit

protocol KSChooseScreenTypeDelegate: NSObjectProtocol {
    func chooseScreenType(selectRow: NSInteger)
}

class KSPickerOrderChooseView: UIView {
    
    weak var delegate: KSChooseScreenTypeDelegate?
    var dataArray: [String] = []
    var selectrow = 0
    private let tableview = UITableView()
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        
        tableview.delegate = self
        tableview.dataSource = self
        tableview.rowHeight = 50
        tableview.separatorStyle = .none
        tableview.register(KSPickerOrderTableViewCell.self, forCellReuseIdentifier: "KSPickerOrderTableViewCell")
        self.addSubview(tableview)
        tableview.snp.makeConstraints { (make) in
            make.left.right.equalTo(0)
            make.top.equalTo(0)
            make.height.equalTo((50 * dataArray.count > Int(KSConstants.kScreenHeight/3*2)) ? KSConstants.kScreenHeight/3*2 : 50 * dataArray.count)
        }
    }
    
    func changeDataArray(array: [String],selectRow: NSInteger) {
        selectrow = selectRow
        self.isHidden = false
        dataArray = array
        tableview.snp.updateConstraints { (make) in
            make.height.equalTo((50 * dataArray.count > Int(KSConstants.kScreenHeight/3*2)) ? KSConstants.kScreenHeight/3*2 : 50 * dataArray.count)
        }
        tableview.reloadData()
    }
    
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension KSPickerOrderChooseView: UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "KSPickerOrderTableViewCell", for: indexPath) as! KSPickerOrderTableViewCell
        let title = dataArray[indexPath.row]
        if selectrow == indexPath.row {
            cell.setTitleAndImg(title: title, isSelect: true)
        } else {
            cell.setTitleAndImg(title: title, isSelect: false)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableview.reloadData()
        self.isHidden = true
        self.delegate?.chooseScreenType(selectRow: indexPath.row)
    }
}
